<template>
  <div class='news-wrapper'>
    <!-- 展示请在微信环境打开 -->
    <section class='news-invalid-onlywechat' v-if='invalidForWechat'>
      请在微信客户端打开
    </section>
    <!-- 展示无权限访问 -->
    <section class='news-invalid-visit' v-if='invalidForVisit'>
      当前为受保护内容，您无权访问
    </section>
    <!-- 正文展示 -->
    <section class='news-detail'
            :class='{noCopy: news.forbidCopy}'
             v-if='!loading'>
      <div class='detail-title'>{{news.title}}</div>
      <div class='detail-subtitle'>
        <span class='sub-item sub-icon'>原创</span>
        <span class='sub-item sub-time'>{{news.createTime ? news.createTime.slice(0, 10) : ''}}</span>
        <span class='sub-item sub-author'>{{news.author}}</span>
      </div>
      <div class='detail-content editor-content' v-html='news.content'></div>
      <!-- 显示阅读数、点赞数、点赞 -->
      <!-- <div class='detail-footer'>
        <div class='detail-data'>
          <div class='data-item'>
            <span class='item-label'>阅读</span>
            <span class='item-content'>{{news.readNum || 0}}</span>
          </div>
          <div class='data-item'>
            <span class='item-label'>点赞</span>
            <span class='item-content'>{{news.thumbUpNum || 0}}</span>
          </div>
        </div>
        <div class='detail-handle'>
          <div class='article-thumbUp'
              :class='{isThumbUped: hasThumbUp}'
              @click='praiseArticle()'>
            <span class='iconfont'>{{hasThumbUp ? '&#xe665;' : '&#xe666;'}}</span><span>点赞</span>
            <span :class='{iconfont: true, dynamic: true, move: isMove1}'>&#xe665;</span>
          </div>
        </div>
      </div> -->
    </section>
    <!-- 图片预览 -->
    <van-image-preview
      v-model="showPreview"
      :start-position='currImgIndex'
      ref='imgPreview'
      :images="imageList"
      @change="onChange"
      closeable>
      <template v-slot:index>{{ currImgIndex + 1+ '/' + imageList.length}}</template>
    </van-image-preview>
  </div>
</template>

<script>
import watermark from '@/assets/js/watermark.js'
import { ImagePreview } from 'vant'
export default {
  name: 'newsDetail',
  data () {
    return {
      loading: true,
      news: {},
      mediaId: '',
      hasCollected: false,
      hasThumbUp: false,
      isMove: false, // 收藏动画
      isMove1: false, // 点赞动画
      isWxClient: false,
      startComment: false,
      msgContent: '',
      invalidForWechat: false,
      invalidForVisit: false,
      userAgent: '',
      userId: '',
      // 图片预览相关
      imageList: [],
      currImgIndex: 0,
      showPreview: false
    }
  },
  components: {
    [ImagePreview.Component.name]: ImagePreview.Component
  },
  methods: {
    onChange (index) {
      this.currImgIndex = index
    },
    previewImg (index) {
      console.log('index: ', index)
      this.currImgIndex = index
      this.showPreview = true
    },
    praiseArticle () {
      // if (!this.hasThumbUp) {
      //   let url = `${this.SERVICE_PORTAL}/Knowledge/article/${this.articleId}/thumbUp`
      //   let param = {
      //     cancel: false,
      //     nickName: localStorage.getItem('fansNickName') || '',
      //     openid: sessionStorage.getItem('openid'),
      //     wxAppid: sessionStorage.getItem('appid')
      //   }
      //   this.$post(url, param).then(res => {
      //     if (res.code === 200) {
      //       this.hasThumbUp = !this.hasThumbUp
      //       this.isMove1 = true
      //       setTimeout(() => {
      //         this.isMove1 = false
      //       }, 2000)
      //     }
      //   })
      // } else {
      //   let url = `${this.SERVICE_PORTAL}/Knowledge/article/${this.articleId}/thumbUp`
      //   let param = {
      //     cancel: true,
      //     nickName: localStorage.getItem('fansNickName') || '',
      //     openid: sessionStorage.getItem('openid'),
      //     wxAppid: sessionStorage.getItem('appid')
      //   }
      //   this.$post(url, param).then(res => {
      //     if (res.code === 200) {
      //       this.hasThumbUp = !this.hasThumbUp
      //     }
      //   })
      // }
    },
    init () {
      this.mediaId = this.$route.params.mediaId
      this.loading = true
      this.$_load.show()
      let url = `${this.SERVICE_PORTAL}/cp/media/${sessionStorage.getItem('agentId')}/newsItem/${this.mediaId}`
      this.$get(url).then(res => {
        if (res.code === 200) {
          if (res.data) {
            this.news = res.data
            this.news.content = this.getProxyForWxMat(this.news.content)
            document.title = this.news.title
            this.$_load.hide()
            console.log('news: ', this.news)
            // 获取当前的运行环境
            this.userAgent = sessionStorage.getItem('userAgent')
            this.userId = sessionStorage.getItem('userId')
            // 只允许在微信客户端打开
            if (this.news.mpClientVisit && this.userAgent === 'normal') {
              this.invalidForWechat = true
              return false
            }
            // 只允许企业成员访问
            if (this.news.accessScope === 1 && !this.userId) {
              this.invalidForVisit = true
              return false
            }
            /**
             * @todo 仅允许‘收件人’访问
             */
            // 正文需要加入水印
            if (this.news.showWatermark) {
              this.$nextTick(() => {
                watermark.set('罗氏诊断专属水印', document.querySelector('.news-detail'))
              })
            }
            // 如果禁止分享，则不显示分享菜单
            if (this.news.hideShareButton) {
              this.setCropToolMenuAndShare({
                showMenuList: [],
                forbitShare: true
              })
            // 否则设置分享参数
            } else {
              this.setCropToolMenuAndShare({
                shareInfo: {
                  title: this.news.title,
                  imgUrl: this.news.picUrl
                }
              })
            }
            this.loading = false
            // 如果没有禁止复制正文，添加图片预览功能
            if (!this.news.forbidCopy) {
              this.$nextTick(() => {
                this.imageList = []
                // 获取所有img标签，并添加点击事件
                let imgs = Array.prototype.slice.call(document.querySelectorAll('img'))
                imgs.forEach((imgDOM, index) => {
                  let src = imgDOM.getAttribute('src')
                  this.imageList.push(src)
                  imgDOM.addEventListener('click', this.previewImg.bind(this, index))
                })
              })
            }
          } else {
            this.$_load.hide()
            this.$toast('该图文已删除')
          }
        } else {
          this.$_load.hide()
        }
      })
    }
  },
  mounted () {
    this.init()
  }
}
</script>

<style lang='stylus' scoped>
@keyframes mymove {
  0% {
    opacity 1
  }
  100% {
    top -20px
    opacity 0
  }
}
.dynamic
  position absolute
  left 0
  top 0
  opacity 0
  &.move
    animation mymove 2s 1
.news-wrapper
  max-width 700px
  margin auto
  .news-invalid-onlywechat,
  .news-invalid-visit
    text-align center
    padding-top 20px
    font-size 14px
  .news-detail
    position relative
    padding 10px 15px 15px
    overflow-x hidden
    &.noCopy
      user-select: none;
    .detail-title
      margin-bottom: 12px
      line-height: 1.4
      font-weight: 400
      font-size: 22px
    .detail-subtitle
      display flex
      flex-wrap wrap
      align-items center
      .sub-item
        margin 0 8px 10px 0
      .sub-icon
        padding: 2px 6px
        border: 1px solid rgba(0,0,0,0.2)
        color: rgba(0,0,0,0.3)
        font-size 12px
        border-radius 10px
      .sub-time, .sub-author
        color rgba(0,0,0,0.3)
        font-size: 14px
      .sub-wechat
        font-size: 14px
        color #607fa6
    .detail-footer
      display flex
      justify-content space-between
      align-items center
      margin-top 10px
      .detail-data
        display flex
        aling-items center
        .data-item
          display flex
          align-items center
          font-size 12px
          margin-right 15px
          .item-label
            color #8c8c8c
            margin-right 5px
          .item-content
            color #8c8c8c
      .detail-handle
        display flex
        align-items center
        font-size 12px
        .article-collect
          position relative
          color #C9CACA
          &.isCollected
            color #86CBBF
          .iconfont
            font-size 12px
            margin-right 3px
        .article-thumbUp
          position relative
          margin-left 20px
          color #C9CACA
          &.isThumbUped
            color #2FB3E3
          .iconfont
            font-size 12px
            margin-right 3px
</style>
